package com.liujie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liujie.common.R;
import com.liujie.entity.Category;
import com.liujie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean save = categoryService.save(category);
        if (save){
            return R.success("添加菜品分类成功");
        }
        return R.error("添加菜品分类失败");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        Page<Category> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,lqw);
        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        boolean update = categoryService.updateById(category);
        if (update){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    @DeleteMapping
    public R<String> delete(long ids){
        boolean remove = categoryService.remove(ids);
        if (remove){
            return R.success("删除成功");
        }
        return R.error("执行异常，删除失败");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryService.list(lqw);
        if (categories.size()>0){
            return R.success(categories);
        }
        return R.error("没有分类");
    }
}
